<template>
  <div>
    <div class="detail" v-if="type == 'add' || type == 'edit'">
      <div style="width: 420px">
        <el-form
          ref="form_task"
          :model="form"
          :rules="type == 'add' || type == 'edit' ? rules : {}"
          label-width="80px"
        >
          <el-form-item label="任务目标" prop="chapterObjectives">
            <el-input
              v-input-restrict
              class="edit_texteara"
              v-if="type == 'add' || type == 'edit'"
              maxlength="500"
              show-word-limit
              :autosize="{ minRows: 5, maxRows: 8 }"
              v-model="form.chapterObjectives"
              type="textarea"
              placeholder="请输入任务目标"
            />
            <div
              v-else
              style="white-space: pre-wrap"
              v-html="form.chapterObjectives"
            ></div>
          </el-form-item>
          <el-form-item label="任务描述" prop="describe">
            <el-input
              v-input-restrict
              v-if="type == 'add' || type == 'edit'"
              maxlength="500"
              class="edit_texteara"
              show-word-limit
              :autosize="{ minRows: 5, maxRows: 8 }"
              v-model="form.describe"
              type="textarea"
              placeholder="请输入任务描述"
            />
            <div
              v-else
              style="white-space: pre-wrap"
              v-html="form.describe"
            ></div>
          </el-form-item>
          <el-form-item label="任务学时" prop="recommendTime">
            <el-input-number
              v-if="type == 'add' || type == 'edit'"
              controls-position="right"
              :min="0"
              :precision="1"
              :step="0.5"
              v-model="form.recommendTime"
              placeholder="请输入"
            />
            <div v-else style="white-space: pre-wrap">
              {{ form.describe }}
            </div>
            时
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-else class="lookDetail">
      <div class="flex item">
        <div class="item_lable">任务目标</div>
        <div
          style="white-space: pre-wrap"
          class="item_value"
          v-html="form.chapterObjectives"
        ></div>
      </div>
      <div class="flex item">
        <div class="item_lable">任务描述</div>
        <div
          style="white-space: pre-wrap"
          class="item_value"
          v-html="form.describe"
        ></div>
      </div>
      <div class="flex item">
        <div class="item_lable">任务学时</div>
        <div style="white-space: pre-wrap" class="item_value">
          {{ form.recommendTime ? form.recommendTime : 0 }}
        </div>
      </div>
    </div>
    <div class="detailbottom flexend">
      <!-- <el-button
        v-preventReClick
        v-if="type == 'add' || type == 'edit'"
        @click="cancel"
        >取 消
      </el-button> -->
      <el-button
        v-preventReClick
        type="primary"
        v-if="type == 'add' || type == 'edit'"
        @click="submitForm(false, true)"
        >保 存
      </el-button>
      <el-button v-preventReClick v-if="type == 'audit'" @click="cancel"
        >取 消
      </el-button>
      
      <el-button
        v-preventReClick
        type="danger"
        v-if="type == 'audit'"
        @click="reject"
        >驳 回
      </el-button>
      <el-button
        v-preventReClick
        type="primary"
        v-if="type == 'audit'"
        @click="audit"
        >通 过
      </el-button>
      <el-button
        v-preventReClick
        type="primary"
        v-if="type == 'detail'"
        @click="cancel"
        >退 出
      </el-button>
    </div>
    <!-- 驳回 -->
    <reject
      :open.sync="rejectOpen"
      :type="1"
      @refresh="reasonDiaReturn"
    ></reject>
    <!-- 审核弹窗 -->
    <auditByRoles
      :open.sync="auditByRoles_open"
      :type="auditByRoles_type"
      :courseId="auditByRoles_courseId"
    >
    </auditByRoles>
  </div>
</template>

<script>
import auditByRoles from "./auditByRoles.vue";
import reject from "@/components/reject";
import {
  getPost_chapterTemporary,
  updatePost_chapterTemporary,
} from "@/api/course/chapter";
import {
  reviewCourseTemporary,
  reviewCourseTemporarybeforeCheck,
} from "@/api/course/course";
import { getPost_chapter } from "@/api/course/officalChapter";
import { del } from "vue";

export default {
  components: { reject, auditByRoles },
  props: {
    type: String,
    courseForm: [Object],
    chapterId: [String, Number],
    tabIndex: [String, Number],
  },
  data() {
    return {
      //审核弹窗
      auditByRoles_open: false,
      auditByRoles_type: 2,
      auditByRoles_courseId: "",
      //
      rejectOpen: false,
      queryParam: "",
      // 表单参数
      form: {
        recommendTime: undefined,
        chapterName: undefined,
        chapterId: undefined,
        ccCourseTaskList: [],
        chapterObjectives: undefined,
        describe: undefined,
        type: 0,
      },
      // 表单校验
      rules: {
        chapterName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.queryParam = this.$route.query;
  },
  beforeDestroy() {
    if (this.tabIndex == 1) {
      console.log("组件被摧毁了");
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        if (this.form.id) {
          this.submitForm(false);
        }
      }
    }
  },
  watch: {
    //监听form.id   来判断同组件切换时   保存上一个内容
    form: {
      handler(newValue, oldValue) {
        //判断有旧的form.id   说明是同组件切换   没有则证明是初次加载该组件
        if (oldValue.id) {
          //判断有旧的form.id  是否变化   有变化说明是组件切换了数据  将旧的id数据保存
          if (oldValue.id != newValue.id) {
            if (this.tabIndex == 1) {
              if (
                this.$route.query.type == "add" ||
                this.$route.query.type == "edit"
              ) {
                console.log("t:oldValue", oldValue);
                this.submitForm(oldValue);
              }
            }
          }
        }
      },
    },
    // 监听章节id
    chapterId: {
      handler(newValue, oldValue) {
        console.log("监听章节id", newValue, oldValue);
        this.getInfo();
      },
      immediate: true,
    },
  },
  methods: {
    /* 驳回组件返回 */
    async reasonDiaReturn(e) {
      let res = await reviewCourseTemporary({
        id: this.courseForm.id,
        approvalState: 0,
        rejected: e,
      });
      this.$modal.msgSuccess("驳回审核成功");
      this.$store.dispatch("tagsView/delView", this.$router.currentRoute);
      setTimeout(() => {
        this.$router.push({ path: "/course/course_temporary" });
      }, 100);
    },
    /* 驳回 */
    async reject() {
      try {
        let before = await reviewCourseTemporarybeforeCheck({
          courseTemporaryId: this.courseForm.id,
        });
        if (before.code == 200) {
          this.rejectOpen = true;
        }
      } catch (error) {}
    },
    /* 通过审核 */
    // <!-- 首先判断是否为 营本级课程 -->
    // <!-- 不是营本级的话 当状态为3初审的时候 培训专员审核 -->
    // <!-- 不是营本级的话 当状态为4复审的时候 品控专员/品控经理审核 -->
    async audit() {
      try {
        let before = await reviewCourseTemporarybeforeCheck({
          courseTemporaryId: this.courseForm.id,
        });
        if (before.code == 200) {
          if (this.$route.query.status == "temporary1") {
            this.auditByRoles_open = true;
            this.auditByRoles_type = 2;
            this.auditByRoles_courseId = this.$route.query.courseTemporaryId;
          } else if (this.$route.query.status == "temporary3") {
            this.auditByRoles_open = true;
            this.auditByRoles_type = 1;
            this.auditByRoles_courseId = this.$route.query.courseTemporaryId;
          } else if (
            this.$route.query.status == "temporary2" ||
            this.$route.query.status == "temporary4"
          ) {
            this.$confirm(`点击确认，通过审核。`, "通过确认", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(async () => {
                const loading = this.$loading({
                  lock: true,
                  text: `正在审核中…`,
                  spinner: "el-icon-loading",
                  background: "rgba(255, 255, 255, 0.6)",
                });
                try {
                  let res = await reviewCourseTemporary({
                    id: this.courseForm.id,
                    approvalState: 1,
                  });
                  if (res.code == 200) {
                    this.$modal.msgSuccess("通过审核成功");
                    this.$store.dispatch(
                      "tagsView/delView",
                      this.$router.currentRoute
                    );
                    setTimeout(() => {
                      this.$router.push({ path: "/course/course_temporary" });
                    }, 100);
                  }
                } finally {
                  loading.close();
                }
              })
              .catch(() => {});
          }
        }
      } catch (error) {}
    },
    /* 获取章节信息(分草稿和正式课程) */
    async getInfo() {
      let res;
      if (this.$route.query.courseId) {
        res = await getPost_chapter(this.chapterId);
      } else {
        res = await getPost_chapterTemporary(this.chapterId);
      }
      if (res && res.data) {
        this.form = res.data;
      }
    },
    /** 提交按钮 修改章节信息*/
    submitForm(e, successMsg = false) {
      const loading = this.$loading({
        lock: true,
        text: "正在保存...",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      if (this.queryParam.type == "edit" || this.queryParam.type == "add") {
        this.$refs["form_task"].validate(async (valid) => {
          if (valid) {
            let form = e ? e : { ...this.form };
            delete form.chapterName;
            delete form.sort;
            try {
              let res = await updatePost_chapterTemporary(form);
              if (res) {
                loading.close();
                if (successMsg) {
                  this.$modal.msgSuccess("保存成功");
                }
              }
            } catch (error) {
              loading.close();
            }
          }
        });
      }
    },
    // 表单重置
    reset() {
      this.form = {
        recommendTime: undefined,
        chapterName: undefined,
        chapterId: undefined,
        chapterObjectives: undefined,
        ccCourseTaskList: [],
        describe: undefined,
        type: 0,
      };
      this.resetForm("form");
    },
    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="scss">
.lookDetail {
  padding: 24px 0 0 40px;
  border-top: 1px solid #ebebeb;
  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;

  .item {
    margin-bottom: 32px;

    .item_lable {
      margin-right: 32px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 22px;
    }

    .item_value {
      width: 696px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 22px;
      white-space: pre-wrap;
    }
  }
}

.detailbottom {
  border-top: 1px solid #ebebeb;
  height: 72px;
  box-sizing: border-box;
  padding: 0 19px 0 37px;
  align-items: center;

  ::v-deep .el-button {
    padding: 0 24px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    border-radius: 8px;
    line-height: 38px;
    height: 38px;
  }
}

.detail {
  padding: 40px 0 0 80px;
  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;
}
.edit_texteara {
  width: 660px;
}
</style>
